package com.employee.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.employee.author.AuthRequired;
import com.employee.controller.vo.JsonResult;
import com.employee.dao.mapper.*;
import com.employee.dao.model.Employee;
import com.employee.utils.page.PageView;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import tk.mybatis.mapper.entity.Example;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 后台接口：用户管理
 */
@RequestMapping("/admin/user")
@RestController
public class AdminUserController {
    
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //注册自定义的编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 查询员工列表
     * @param request
     * @return
     */
    @RequestMapping("list")
    @AuthRequired
    public JsonResult userList(@RequestBody JSONObject request, HttpServletRequest httpServletRequest)  {
        JsonResult result = new JsonResult(true, 200, "查询成功");
        PageView<Employee> page = new PageView<>();
        page = page.startPage(request);
        String kw = request.getString("kw");
        Example example = new Example(Employee.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(kw)){
            criteria.andLike("realName", "%"+kw+"%");
        }
        criteria.andNotEqualTo("position", 99);//99是管理员角色
        //判断当前用户是否为管理员
        Employee loginEmp = (Employee) httpServletRequest.getAttribute("loginAdmin");
        if(loginEmp.getPosition()==99){
            //管理员，查看所有员工
//            criteria.andEqualTo("position", 99);
        }else if(loginEmp.getPosition()==2){
            //部长，查看自己部门
            criteria.andEqualTo("deptId", loginEmp.getDeptId());
        }
        List<Employee> list = employeeMapper.selectByExampleAndRowBounds(example, new RowBounds(page.getFirstResult(), page.getMaxresult()));
        for (Employee employee : list){
            //设置部门信息
            employee.setDept(departmentMapper.selectByPrimaryKey(employee.getDeptId()));
        }
        page.setRecords(list);
        page.setTotalrecord(employeeMapper.selectCountByExample(example));
        result.setData(page);
        return result;
    }

    /**
     * 查询员工详情
     * @param userId
     * @return
     */
    @RequestMapping("detail")
    public JsonResult detail(Integer userId) {
        JsonResult result = new JsonResult(true, 200, "查询成功");
        Employee user = employeeMapper.selectByPrimaryKey(userId);
        result.setData(user);
        return result;
    }

    @RequestMapping("getAll")
    public JsonResult getAlluser(){
        JsonResult result = new JsonResult(true, 200, "查询成功");
        List<Employee> list = employeeMapper.selectAll();
        result.setData(list);
        return result;
    }

    /**
     * 查询员工信息
     * @param userId
     * @return
     */
    @RequestMapping("info/{userId}")
    public JsonResult info(@PathVariable Integer userId) {
        JsonResult result = new JsonResult(true, 200, "查询成功");
        Employee user = employeeMapper.selectByPrimaryKey(userId);
        result.setData(user);
        return result;
    }

    /**
     * 更新员工信息
     * @param employee
     * @return
     */
    @RequestMapping("save")
    public JsonResult saveOrUpdateApartment(@RequestBody Employee employee) {
        JsonResult result = new JsonResult(true, 200, "操作成功");
        try {
            if(employee.getEmployeeId()==null){
                employeeMapper.insertSelective(employee);
            }else{
                employeeMapper.updateByPrimaryKeySelective(employee);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("更新失败");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 更新员工状态
     * @param jsonObject
     * @return
     */
    @RequestMapping("update2")
    public JsonResult updateUserStatus(@RequestBody JSONObject jsonObject){
        JsonResult result = new JsonResult(true, 200, "更新成功");
        Integer employeeId = jsonObject.getInteger("employeeId");
        Integer status = jsonObject.getInteger("status");
        Employee employee = employeeMapper.selectByPrimaryKey(employeeId);
        employee.setEmployStatus(-1);
        employeeMapper.updateByPrimaryKeySelective(employee);
        result.setData(employee);
        return result;
    }
}
